package com.jinke.api.modules.third.dqpost.util;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jinke.api.common.annotation.Apilog;
import com.jinke.api.common.util.CommonUtil;
import com.jinke.api.modules.third.dqpost.model.request.*;
import com.jinke.api.modules.third.ezeeship.model.request.EstimateRateRequest;
import com.jinke.api.modules.app.util.MathUtil;
import com.jinke.api.modules.third.ezeeship.util.EzeeShipUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
@RequiredArgsConstructor
public class DqpostlUtil {



    public static final int NUM_PLACES = 2;
    public static final RoundingMode ROUND_TYPE = RoundingMode.CEILING;
    public static final String HTTPS_API_DQPOST_COM_ORDER_CREATE = "https://api.dqpost.com/order/create";
    public static final String RATE = "https://api.dqpost.com/order/rate";

    private static String sendPostRequest(String url, String requestBody) throws IOException {
        HttpURLConnection connection = null;
        try {
            String seq = CommonUtil.getOrderNo();

            // 创建连接
            URL apiUrl = new URL(url);
            if ("true".equals(System.getenv("local"))) {
                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", 10809));
                connection = (HttpURLConnection) apiUrl.openConnection(proxy);
            } else {
                connection = (HttpURLConnection) apiUrl.openConnection();
            }


            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("apikey", "021fabf5e118b17d77cb77ba04d97a37");
            connection.setDoOutput(true);

            // 写入请求体
            try (OutputStream outputStream = connection.getOutputStream()) {
                outputStream.write(requestBody.getBytes("UTF-8"));
            }

            // 获取响应
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                return response.toString();
            }
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    private static String sendGetRequest(String url) throws IOException {
        HttpURLConnection connection = null;
        try {
            String seq = CommonUtil.getOrderNo();

            URL apiUrl = new URL(url);
            if ("true".equals(System.getenv("local"))) {
                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", 10809));
                connection = (HttpURLConnection) apiUrl.openConnection(proxy);
            } else {
                connection = (HttpURLConnection) apiUrl.openConnection();
            }

            connection.setRequestMethod("GET");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("apikey", "021fabf5e118b17d77cb77ba04d97a37");
            // 获取响应
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                return response.toString();
            }
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }


    /**
     * 估价
     *
     * @param estimateRateRequest
     * @return
     */
    @Apilog(requestTypeName = "DqPost-估价")
    public String getPrice(EstimateRateRequest estimateRateRequest) {
        CreateOrderRequest dto = getCreateOrderRequest(estimateRateRequest);
        String param = JSON.toJSONString(dto);
        String orderNO = estimateRateRequest.getOrderNO();
        try {
            // 发送POST请求
            log.info("DqPost估价参数--------------->,{},{}", orderNO, param);
            String response = sendPostRequest(RATE, param);
            log.info("DqPost估价响应--------------->,{},{}", orderNO, response);
            return response;
        } catch (IOException e) {
            log.info("DqPost估价异常--------------->,{},{}", orderNO, e.getMessage());
        }
        return Strings.EMPTY;
    }

    @NotNull
    private CreateOrderRequest getCreateOrderRequest(EstimateRateRequest estimateRateRequest) {
        CreateOrderRequest createOrderRequest = new CreateOrderRequest();
        createOrderRequest.setServiceCode(estimateRateRequest.getServiceCode());
        CreateOrderRequest.Address sender = new CreateOrderRequest.Address();
        EstimateRateRequest.Address from = estimateRateRequest.getFrom();
        sender.setName(from.getPersonName());
        sender.setCountry(from.getCountryCode());
        sender.setPhone(from.getPhone());
        sender.setCity(from.getCity());
        sender.setState(from.getStateCode());
        sender.setZipcode(from.getZipCode());
        List<String> addressLines = new ArrayList<>();
        addressLines.add(from.getAddressLine1());
        if (StringUtils.isNotEmpty(from.getAddressLine2())) {
            addressLines.add(from.getAddressLine2());
        }
        sender.setAddress(addressLines);

        CreateOrderRequest.Address recipient = new CreateOrderRequest.Address();
        EstimateRateRequest.Address to = estimateRateRequest.getTo();
        recipient.setName(to.getPersonName());
        recipient.setCountry(to.getCountryCode());
        recipient.setPhone(to.getPhone());
        recipient.setCity(to.getCity());
        recipient.setState(to.getStateCode());
        recipient.setZipcode(to.getZipCode());
        List<String> addressLines2 = new ArrayList<>();
        addressLines2.add(to.getAddressLine1());
        if (StringUtils.isNotEmpty(to.getAddressLine2())) {
            addressLines2.add(to.getAddressLine2());
        }
        recipient.setAddress(addressLines2);

        CreateOrderRequest.MyPackage myPackage = new CreateOrderRequest.MyPackage();
        List<EstimateRateRequest.Parcel> requestParcels = estimateRateRequest.getParcels();
        final BigDecimal[] totalWeight = {BigDecimal.ZERO};
        List<CreateOrderRequest.PackageDimensions> parcelsList = requestParcels.stream().map(x -> {
            // 创建Parcels对象
            CreateOrderRequest.PackageDimensions parcels = new CreateOrderRequest.PackageDimensions();
            //  parcels.setBoxnote("label reference");
            BigDecimal weight = BigDecimal.valueOf(Double.parseDouble(x.getWeight()));
            // 转换成镑
            if ("kg".equals(x.getMassUnit())) {
                weight = MathUtil.kg2lb(weight);
            }
            parcels.setWeight(weight);

            // 转换成in
            BigDecimal length = BigDecimal.valueOf(Double.parseDouble(x.getLength()));
            BigDecimal width = BigDecimal.valueOf(Double.parseDouble(x.getWidth()));
            BigDecimal height = BigDecimal.valueOf(Double.parseDouble(x.getHeight()));
            if ("cm".equals(x.getDistanceUnit())) {
                length = MathUtil.cm2in(length);
                width = MathUtil.cm2in(width);
                height = MathUtil.cm2in(height);
            }

            parcels.setLength(length);
            parcels.setWidth(width);
            parcels.setHeight(height);
            totalWeight[0] = totalWeight[0].add(weight);

            return parcels;
        }).collect(Collectors.toList());
        myPackage.setDimensions(parcelsList);
        createOrderRequest.setMyPackage(myPackage);
        createOrderRequest.setSender(sender);
        createOrderRequest.setRecipient(recipient);

        createOrderRequest.setOrderNo(estimateRateRequest.getPlatformNo());

        EstimateRateRequest.LabelExtra extra = estimateRateRequest.getExtra();

        if (extra != null) {
            String reference = extra.getReference();
            if (StringUtils.isNotBlank(reference) && StringUtils.isNotEmpty(extra.getReference2())) {
                reference = reference + "; " + extra.getReference2();
            }

            if (StringUtils.isNotBlank(reference)) {
                reference = reference.length() >= 50 ? reference.substring(0, 49) : reference;
                createOrderRequest.setRemark(reference);
            }
        }

        return createOrderRequest;
    }

    public String getLabels(GetLabelsRequest request) {
        // 设置API端点URL
        String apiUrl = "https://api.dqpost.com/order/label?platform_no=" + request.getPlatformNo(); // 替换成实际的API URL



        try {
            log.info("------------DqPost获取面单参数--------------->,{}", request.getPlatformNo());

            String response = sendGetRequest(apiUrl);
            // 处理响应
            log.info("------------DqPost获取面单响应--------------->,{}", response);
            return response;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Strings.EMPTY;
    }

    @Apilog(requestTypeName = "DqPost-取消")
    public String cancelLabel(String objectId, String orderNo) {
        String apiUrl = "https://api.dqpost.com/order/cancel?platform_no=" + objectId;
        try {
            log.info("------------DqPost取消参数--------------->,{},{}", orderNo, objectId);
            String response = sendGetRequest(apiUrl);
            log.info("------------DqPost取消响应--------------->,{},{}", orderNo, response);
            return response;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Strings.EMPTY;
    }


    @Apilog(requestTypeName = "DqPost-下单")
    public String createOrder(EstimateRateRequest estimateRateRequest) {
        CreateOrderRequest dto = getCreateOrderRequest(estimateRateRequest);
        String param = JSON.toJSONString(dto);
        String orderNO = estimateRateRequest.getOrderNO();
        try {
            // 发送POST请求
            log.info("------------DqPost 下单请求------------>,{},{}", orderNO, param);
            String response = sendPostRequest(HTTPS_API_DQPOST_COM_ORDER_CREATE, param);
            // 处理响应
            log.info("------------DqPost 下单响应------------>,{},{}", orderNO, response);
            return response;
        } catch (IOException e) {
            log.info("------------DqPost 下单异常------------>,{}", orderNO);
        }
        return Strings.EMPTY;
    }

    public String tracking(String tracingNo) {
        // 设置API端点URL
        String apiUrl = "https://sj.tanwapost.com/xapi/tracking.php"; // 替换成实际的API URL

        TrackingRequest request = new TrackingRequest();
        request.setTrackingno(tracingNo);
        request.setApikey("tw_4838");
        String requestBody = JSON.toJSONString(request);

        try {
            // 发送POST请求
            log.info(requestBody);
            String response = sendPostRequest(apiUrl, requestBody);
            // 处理响应
            log.info("Response: " + response);
            return response;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Strings.EMPTY;
    }

    public String getChannel() {
        // 设置API端点URL
        String apiUrl = "https://sj.tanwapost.com/xapi/channel.php"; // 替换成实际的API URL

        // 将OrderRequest对象转换为JSON字符串
        // 创建OrderRequest对象
        BaseEntity orderRequest = new BaseEntity();

// 设置属性值
        orderRequest.setApikey("tw_4838");

        String requestBody = JSON.toJSONString(orderRequest);

        try {
            // 发送POST请求
            log.info(requestBody);
            String response = sendPostRequest(apiUrl, requestBody);
            log.info("Response: " + response);
            // 处理响应
            return response;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

}
